import { defineStore } from 'pinia'
import store from '../index'
import { ref, watch } from 'vue'
import i18n from '@/i18n'
export const useAppStore = defineStore(
  'appStore',
  () => {
    const titleName = '趋势预测与辅助决策系统'
    const isRender = ref(false)
    const sidebarOpened = ref(true)
    const language = ref('zh')
    const tagsViewList = ref([])
    const triggerSidebarOpened = () => {
      sidebarOpened.value = !sidebarOpened.value
    }
    const setLanguage = (lang) => {
      language.value = lang
    }
    const addTagsViewList = (tag) => {
      const isFind = tagsViewList.value.find((item) => {
        return item.path === tag.path
      })
      // 若不重复
      if (!isFind) {
        tagsViewList.value.push(tag)
      }
    }
    const removeTagsView = (payload) => {
      if (payload.type === 'index') {
        tagsViewList.value.splice(payload.index, 1)
        return
      } else if (payload.type === 'other') {
        tagsViewList.value.splice(payload.index + 1, tagsViewList.value.length - payload.index + 1)
        tagsViewList.value.splice(0, payload.index)
      } else if (payload.type === 'right') {
        tagsViewList.value.splice(payload.index + 1, tagsViewList.value.length - payload.index + 1)
      } else {
        // 关闭所有标签
        tagsViewList.value = []
      }
    }
    // 监听
    watch(language, () => {
      tagsViewList.value.forEach(
        (tag) => (tag.title = i18n.global.t('msg.route.' + tag.meta.title))
      )
    })

    return {
      titleName,
      isRender,
      sidebarOpened,
      triggerSidebarOpened,
      language,
      setLanguage,
      tagsViewList,
      addTagsViewList,
      removeTagsView
    }
  },
  {
    persist: {
      paths: ['language']
    }
  }
)
